#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
# @Time    : 2022/7/24 6:11 下午
# @Author  : super_gou
# @File    : sendEmail.py
import smtplib, time, os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
class SendEmail():

    def __init__(self):
        # 第一步，配置邮箱属性
        # 发送邮箱
        self.sender = '1162186427@qq.com'
        # 接收邮箱
        self.receiver = '13126890956@163.com'
        # 发送邮箱主题
        t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.subject = '自动化测试结s果_' + t

        # 发送邮箱服务器
        #self.smtpserver = 'smtp.126.com'
        self.smtpserver = 'smtp.qq.com"'

        # 发送邮箱用户名/密码
        self.username = ''
        # 这里密码使用pop3的授权码
        self.password = ''

    def __config(self,file):
        # 第二步，准备附件，增加附件，组装邮件内容和标题，中文参数需要'utf-8'，单字节字符不需要
        # 附件赋值
        # 读取html文件内容
        with open(file, 'rb') as f:
            mail_body = f.read()
            # 组装邮件内容和标题
            self.msg = MIMEMultipart()
            # 添加附件内容
            att = MIMEText(mail_body, 'plain', 'utf-8')
            att["Content-Type"] = 'application/octet-stream'
            att['Content-Disposition'] = 'attachment;filename = result.html'
            self.msg.attach(att)
            # 添加邮件的文本内容
            content = '这是第一次使用Python 邮件发送附件测试哦...'
            self.msg.attach(MIMEText(content, 'plain', 'utf-8'))
            self.msg['Subject'] = Header(self.subject, 'utf-8')
            self.msg['From'] = self.sender
            self.msg['To'] = self.receiver

    def send(self,file):
        self.__config(file)
        # 第三步：登录并发送邮箱
        try:
            # 1、实例化
            s = smtplib.SMTP()
            # 2、连接smtp服务器
            s.connect(self.smtpserver)
            # 3、登录邮箱
            s.login(self.username, self.password)
            # 4、设置发件人，收件人，邮件内容
            s.sendmail(self.sender, self.receiver, self.msg.as_sstring())
        except Exception as msg:
            print('邮件发送失败！%s' % msg)
        else:
            print('邮件发送成功')
        finally:
            s.quit()


if __name__ == '__main__':
    # 调试发送邮件
    ce = SendEmail()
    ce.send()